"""
主路由模块
"""
import os
import sys
import threading
import time
from pathlib import Path
from flask import Blueprint, request, jsonify, send_file, render_template, current_app

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from utils.file_utils import secure_filename, extract_class_name
from services.jar_service import JarSearchService
from services.excel_service import ExcelService
from services.progress_service import progress_service

main_bp = Blueprint('main', __name__)

@main_bp.route('/')
def index():
    """首页"""
    return render_template('index.html')

@main_bp.route('/upload', methods=['POST'])
def upload_files():
    """处理文件上传"""
    if 'jar_file' not in request.files or 'class_files' not in request.files:
        return jsonify({'error': '缺少必要的文件'}), 400
    
    jar_file = request.files['jar_file']
    class_files = request.files.getlist('class_files')
    
    if jar_file.filename == '':
        return jsonify({'error': '未选择jar文件'}), 400
    
    if not class_files or all(f.filename == '' for f in class_files):
        return jsonify({'error': '未选择class文件'}), 400
    
    # 生成唯一的任务ID
    task_id = f"task_{int(time.time() * 1000)}"
    
    try:
        # 保存jar文件
        jar_filename = secure_filename(jar_file.filename)
        jar_path = os.path.join(
            current_app.config['UPLOAD_FOLDER'], 
            f"{task_id}_{jar_filename}"
        )
        jar_file.save(jar_path)
        
        # 提取文件名列表（支持所有文件类型）
        file_names = []
        uploaded_file_names = []  # 保存上传的完整文件名列表（用于未匹配文件）
        for class_file in class_files:
            if class_file.filename:
                filename = secure_filename(class_file.filename)
                uploaded_file_names.append(filename)
                # 提取文件名（不含扩展名）用于匹配
                file_name = extract_class_name(filename)
                file_names.append(file_name)
        
        if not file_names:
            return jsonify({'error': '没有有效的文件'}), 400
        
        # 获取配置值（在应用上下文中获取，避免在线程中访问current_app）
        upload_folder = current_app.config['UPLOAD_FOLDER']
        results_folder = current_app.config['RESULTS_FOLDER']
        
        # 在后台线程中处理匹配
        def process_match():
            try:
                # 初始化进度
                progress_service.init_progress(task_id, total=0)
                progress_service.update_progress(task_id, status='starting')
                
                # 创建JAR搜索服务
                jar_service = JarSearchService(upload_folder)
                
                # 搜索匹配
                matches = jar_service.search_in_jar(
                    jar_path, 
                    file_names, 
                    Path(jar_filename).stem, 
                    task_id
                )
                
                # 找出匹配上的文件名（完整文件名和文件名不含扩展名都考虑）
                matched_file_names = set()
                for match in matches:
                    matched_file_names.add(match['filename'])
                    # 也添加不含扩展名的文件名，用于匹配
                    if '.' in match['filename']:
                        matched_file_names.add(match['filename'].rsplit('.', 1)[0])
                
                # 找出未匹配的文件（检查完整文件名和文件名不含扩展名）
                unmatched_files = []
                for filename in uploaded_file_names:
                    # 检查完整文件名和文件名不含扩展名是否都在匹配结果中
                    file_name_no_ext = filename.rsplit('.', 1)[0] if '.' in filename else filename
                    if filename not in matched_file_names and file_name_no_ext not in matched_file_names:
                        unmatched_files.append(filename)
                
                # 生成Excel文件（包含匹配结果和未匹配文件）
                excel_filename = f"{task_id}_results.xlsx"
                excel_path = os.path.join(results_folder, excel_filename)
                
                excel_service = ExcelService()
                excel_service.generate_excel(matches, unmatched_files, excel_path)
                
                # 更新进度
                progress_service.update_progress(task_id, status='completed')
                progress_service.set_excel_filename(task_id, excel_filename)
            
            except Exception as e:
                progress_service.update_progress(task_id, status=f'error: {str(e)}')
            
            finally:
                # 清理上传的jar文件
                try:
                    if os.path.exists(jar_path):
                        os.remove(jar_path)
                except:
                    pass
        
        # 启动后台处理线程
        thread = threading.Thread(target=process_match)
        thread.daemon = True
        thread.start()
        
        return jsonify({
            'task_id': task_id,
            'message': '文件上传成功，开始处理'
        })
    
    except Exception as e:
        return jsonify({'error': f'上传失败: {str(e)}'}), 500

@main_bp.route('/progress/<task_id>')
def get_progress(task_id):
    """获取处理进度"""
    if not progress_service.is_task_exists(task_id):
        return jsonify({'error': '任务不存在'}), 404
    
    progress = progress_service.get_progress(task_id)
    return jsonify(progress)

@main_bp.route('/download/<task_id>')
def download_excel(task_id):
    """下载Excel结果文件"""
    if not progress_service.is_task_exists(task_id):
        return jsonify({'error': '任务不存在'}), 404
    
    if not progress_service.is_task_completed(task_id):
        return jsonify({'error': '处理未完成'}), 400
    
    excel_filename = progress_service.get_excel_filename(task_id)
    if not excel_filename:
        return jsonify({'error': '文件不存在'}), 404
    
    excel_path = os.path.join(current_app.config['RESULTS_FOLDER'], excel_filename)
    if not os.path.exists(excel_path):
        return jsonify({'error': '文件不存在'}), 404
    
    return send_file(excel_path, as_attachment=True, download_name=excel_filename)

